<template>
  <div>
    {{ leftTime }}
  </div>
</template>

<script>
import DateUtil from "@/framework/infra/util/DateUtil";

export default {
  name: "LeftTimeCounter",
  props: {
    value: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      leftTime: this.formatLeftTime(this.value)
    }
  },
  created() {
    this.doStart()
  },
  destroyed() {
    this.clearTime()
  },
  methods: {
    clearTime() {
      if (this.timeFlag) {
        clearTimeout(this.timeFlag)
        this.timeFlag = null
      }
    },
    startCountLeftTime() {
      const parsedSeconds = Math.floor((new Date().getTime() - this._startTime) / 1000)
      this.leftTime = this.value === null || this.value === '' ? '' : this.formatLeftTime(this.value - parsedSeconds)
      this.timeFlag = setTimeout(this.startCountLeftTime, 1000)
    },
    formatLeftTime(v) {
      if (!v || v <= 0) {
        return '已结束'
      }
      return DateUtil.formatLeftTime(v)
    },
    doStart() {
      this.clearTime()
      this._startTime = new Date().getTime()
      this.startCountLeftTime()
    }
  }
}
</script>

<style scoped>

</style>
